package com.liuyi.util;


import java.io.UnsupportedEncodingException;
import java.sql.Date;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;



@RestController
public class ALiYunUtils {
	
	@RequestMapping(value = "getAliyunToken", method = RequestMethod.POST)
	public JSONObject getAliyunToken() throws UnsupportedEncodingException {
		String endpoint = "oss-cn-shanghai.aliyuncs.com";//上海外网节点
        String accessId = "LTAIopKd4znbz2R7";
        String accessKey = "jm1gtuwFpGBuHJgBWgHLT0YbZ75636";
        String bucketName = "liuyixing-app";
        String dir = "user-dir";
        String host = "http://" + bucketName + "." + endpoint;
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
    	long expireTime = 30;
    	long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

        String postPolicy = client.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = postPolicy.getBytes("utf-8");
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = client.calculatePostSignature(postPolicy);
        
        JSONObject jsonObject = new JSONObject();
		jsonObject.put("accessid", accessId);//指的用户请求的accessid。注意仅知道accessid, 对数据不会有影响。
		jsonObject.put("policy", encodedPolicy);//指的是用户表单上传的策略policy，是经过base64编码过的字符串。
		jsonObject.put("signature", postSignature);//是对上述第三个变量policy签名后的字符串。
		jsonObject.put("dir", dir);
		jsonObject.put("host", host);//指的是用户要往哪个域名发往上传请求。
		jsonObject.put("expire", String.valueOf(expireEndTime / 1000));//指的是当前上传策略失效时间，这个变量并不会发送到OSS，因为这个已经指定在policy里面
		return CommonUtil.successJson(jsonObject);
	}
}
